package com.example.admin.testdemo.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.example.admin.testdemo.R;
import com.example.admin.testdemo.adapter.MonitorListAdapter;
import com.example.admin.testdemo.constant.Constant;
import com.example.admin.testdemo.dao.TempData;
import com.example.admin.testdemo.rs232.Cmd;
import com.example.admin.testdemo.rs232.Command;
import com.example.admin.testdemo.rs232.RecDataHandle;
import com.example.admin.testdemo.rs232.Serial;
import com.example.admin.testdemo.util.HandleMonitorResult;
import com.example.admin.testdemo.util.ThreadUtils;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThjTestActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private static String TAG = "ThjTestActivity";
    private GridView gv;
    private Serial serial;
    private EditText et_hds;
    private Button btn_save;
    private Button btn_query;
    private Button btn_chck;
    private MonitorListAdapter adapter;
    private boolean isQuery = false;
    private boolean isCheck = false;
    private boolean isRepeat = false;
    private int timeOut = 5000;
    private int delay = 5000;
    private int address = 1;
    private int layer = 0;
    private int row = 0;
    private TextView tv_mainboardCmd;
    private TextView tv_monitorSerial;
    private TextView tv_monitorStatus;
    private TextView tv_monitorStep;
    private TextView tv_errorCode;
    private TextView tv_mainboardCheck;


    private ScheduledExecutorService scheduledThreadPool;
    private Serial.DataCallback callback = new Serial.DataCallback() {
        @Override
        public void onDataReceived(byte[] buffer, int size) {
            if (buffer[0] == (byte) 0x3B && buffer[1] == (byte) 0xB3) {
                Log.e(TAG, "接收：" + Command.printByteInfo(buffer));
                if (isRepeat) {
                    sendMutilComd(buffer);
                }
                if (buffer[5] == (byte) 0xB9) {
//                    setEnbleQuery(buffer);
                    if(buffer[8] == (byte) 0x00){
                        isCheck=false;
                    }
                    checkGoods(buffer);
                } else if (buffer[5] == (byte) 0xA6) {
                    showMonitorInfo(buffer);
                } else if (buffer[5] == (byte) 0xA5) {
//                    showSaveInfo(buffer);
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thj_test);
        initView();
        initData();
    }


    private void showMonitorInfo(byte[] buffer) {
        HandleMonitorResult.showInfo(this, buffer);
    }

    private void sendMutilComd(byte[] data) {
        if (RecDataHandle.handleMutComd(data)) {
            isRepeat = false;
            isQuery = true;
            isCheck=true;
        }
    }

    private void setEnbleQuery(byte[] data) {
        if (data[0] == (byte) 0x3B && data[1] == (byte) 0xB3 && data[5] == (byte) 0xB9 &&
                data[7] == (byte) 0x00) {
            isQuery = false;
        } else if (data[0] == (byte) 0x3B && data[1] == (byte) 0xB3 && data[5] == (byte) 0xB9 &&
                data[7] == (byte) 0x01) {
            isQuery = true;
        }
    }

    private void checkGoods(byte[] data) {
        String[] ttt = MainBoardUtil.showMainBoardInfo(data);
        setMainBoardTv(ttt);
    }


    private void showSaveInfo(final byte[] buffer) {
        if (buffer[0] == (byte) 0x3B && buffer[5] == (byte) 0xA5) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int hds = (int) buffer[7];
                    int cs = (int) buffer[6];
                    Log.e(TAG, "层数：" + cs + "层数：" + hds);
                    session.setString(Constant.CONFIG_HDS, Integer.toString(hds));
                    session.setString(Constant.CONFIG_CS, Integer.toString(cs));
                    setToast("设置成功");
                }
            });
        }
    }

    private void setTimeOut() {
        timeOut = 7000;
    }


    private void initData() {
        serial = Serial.getSerialInstance();
        serial.setCallback(callback);
        et_hds.setText(session.getString(Constant.CONFIG_HDS, "10"));
    }

    private void startTimer() {
        if (scheduledThreadPool == null) {
            scheduledThreadPool = new ScheduledThreadPoolExecutor(1);
        }
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
//                if (isQuery) {
////                    timeOut -= delay;
////                    if (timeOut < 0) {
////                        isQuery = false;
////                        setTimeOut();
////                    }
//                    queryMainStatus();
//                }
// else if (isRepeat) {
//                    sendAgainComd(address, layer, row);
//                }
            }
        }, 0, delay, TimeUnit.MILLISECONDS);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
//                Log.e(TAG, "isCheck=" + isCheck);
                if (isCheck) {
                    setMainBoardTv(null);
                    queryMainStatus();
//                    test();
                }else  if (isRepeat) {
                    sendAgainComd(address, layer, row);
                }

            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }

    private void initView() {
        tv_mainboardCmd = findViewById(R.id.tv_mainboardCmd);
        tv_monitorSerial = findViewById(R.id.tv_monitorSerial);
        tv_monitorStatus = findViewById(R.id.tv_monitorStatus);
        tv_monitorStep = findViewById(R.id.tv_monitorStep);
        tv_errorCode = findViewById(R.id.tv_errorCode);
        tv_mainboardCheck = findViewById(R.id.tv_mainboardCheck);
        btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);
        btn_query = findViewById(R.id.btn_query);
        btn_query.setOnClickListener(this);
        btn_chck = findViewById(R.id.btn_chck);
        btn_chck.setOnClickListener(this);
        et_hds = findViewById(R.id.et_hds);
        gv = findViewById(R.id.gv);
        gv.setOnItemClickListener(this);
        adapter = new MonitorListAdapter(ThjTestActivity.this, TempData.getMonitors(8, 12));
        gv.setAdapter(adapter);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String temp = adapter.getItem(position);
        String[] tt = temp.split("-");
        address = 1;
        layer = Integer.parseInt(tt[0]);
        row = Integer.parseInt(tt[1]);
        sendCommand(address, layer, row);
    }

    private void sendCommand(int add, int x, int y) {
        if (serial != null) {
            isRepeat = true;
            serial.sendData(Cmd.outGoodsDefaultCmd(add, x, y));

        }
    }


    private void sendAgainComd(int address, int layer, int row) {
        sendCommand(address, layer, row);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (scheduledThreadPool != null) {
            scheduledThreadPool.shutdown();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                setRow();
                break;
            case R.id.btn_query:
                setMainBoardTv(null);
                queryMainStatus();
                break;
            case R.id.btn_chck:
                if (bCeck) {
                    bCeck = false;
                    isCheck = true;
                    btn_chck.setText("光眼检测中");
                } else {
                    bCeck = true;
                    isCheck = false;
                    btn_chck.setText("光眼测试");
                }
                break;
        }
    }

    boolean bCeck = true;

    private void queryMainStatus() {
        if (serial != null) {
            serial.sendData(Cmd.queryMainboardStatus(1));
            Log.e(TAG, "查询主板状态");
        } else {
            Log.e(TAG, "主板未连接");
        }
    }

    private void setRow() {
        String hh = et_hds.getText().toString();
        if (!TextUtils.isEmpty(hh)) {
            if (serial != null) {
                serial.sendData(Cmd.setRowNum(1, Integer.parseInt(hh)));

            } else {
                setToast("下位机未连接");
            }
        } else {
            setToast("货道数不能为空");
        }
    }



    private void setMainBoardTv(final String[] temp) {
        if(ThreadUtils.isInMainThread()){
            setTvAll(temp);
        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setTvAll(temp);
                }
            });
        }

    }

    private void setTvAll(String[] temp){
        if (temp == null) {
            tv_mainboardCmd.setText("");
            tv_monitorSerial.setText("");
            tv_monitorStatus.setText("");
            tv_monitorStep.setText("");
            tv_errorCode.setText("");
            tv_mainboardCheck.setText("");
        } else {
            tv_mainboardCmd.setText(temp[0]);
            tv_monitorSerial.setText(temp[1]);
            tv_monitorStatus.setText(temp[2]);
            tv_monitorStep.setText(temp[3]);
            tv_errorCode.setText(temp[4]);
            tv_mainboardCheck.setText(temp[5]);
        }
    }

    private void saveLog(String log){
//        LogcatHelper.LogDumper dumper=LogcatHelper.LogDumper;
    }


}
